<template>
  <div class="user-management-container">
    <el-card class="user-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="card-title">
              <el-icon class="title-icon"><User /></el-icon>
              用户管理
            </h2>
            <el-text class="subtitle" type="info">管理系统用户账户和权限</el-text>
          </div>
          <div class="header-actions">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索用户..."
                size="default"
                class="search-input"
                clearable
                @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button
                type="primary"
                size="default"
                @click="addUser"
                :icon="Plus"
                class="add-btn"
            >
              新增用户
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <!-- 快速筛选栏 -->
        <div class="filter-bar" v-if="showFilters">
          <div class="filter-group">
            <el-text class="filter-label">角色：</el-text>
            <el-radio-group v-model="roleFilter" @change="handleFilterChange" size="small">
              <el-radio-button :value="null">全部</el-radio-button>
              <el-radio-button :value="1">管理员</el-radio-button>
              <el-radio-button :value="0">普通用户</el-radio-button>
            </el-radio-group>
          </div>
          <div class="filter-group">
            <el-text class="filter-label">状态：</el-text>
            <el-radio-group v-model="statusFilter" @change="handleFilterChange" size="small">
              <el-radio-button :value="null">全部</el-radio-button>
              <el-radio-button :value="0">活跃</el-radio-button>
              <el-radio-button :value="1">冻结</el-radio-button>
            </el-radio-group>
          </div>
          <el-button
              text
              @click="resetFilters"
              size="small"
              :icon="RefreshRight"
              class="reset-filter-btn"
          >
            重置筛选
          </el-button>
        </div>

        <el-table
            :data="filteredUserList"
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
            stripe
            :border="false"
            class="modern-table"
            empty-text="暂无用户数据"
            :default-sort="{ prop: 'id', order: 'ascending' }"
        >
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column
              prop="id"
              label="ID"
              width="80"
              align="center"
              sortable
          />

          <el-table-column
              prop="avatar"
              label="头像"
              width="80"
              align="center"
          >
            <template #default="scope">
              <el-avatar
                  :size="40"
                  :src="scope.row.avatar"
                  class="user-avatar"
              >
                <el-icon><User /></el-icon>
              </el-avatar>
            </template>
          </el-table-column>

          <el-table-column
              prop="userName"
              label="用户信息"
              min-width="200"
          >
            <template #default="scope">
              <div class="user-info">
                <div class="user-name">{{ scope.row.userName }}</div>
                <div class="user-meta">
                  <el-text size="small" type="info">
                    ID: {{ scope.row.id }} |
                    创建时间: {{ formatDate(scope.row.createTime) }}
                  </el-text>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              prop="role"
              label="角色"
              width="120"
              align="center"
          >
            <template #default="scope">
              <el-tag
                  :type="getRoleTagType(scope.row.role)"
                  effect="light"
                  round
              >
                <el-icon class="tag-icon">
                  <component :is="getRoleIcon(scope.row.role)" />
                </el-icon>
                {{ scope.row.role === 1 ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
              prop="status"
              label="状态"
              width="100"
              align="center"
          >
            <template #default="scope">
              <el-tag
                  :type="scope.row.status === 0 ? 'success' : 'danger'"
                  effect="light"
                  round
              >
                <span class="status-dot" :class="scope.row.status === 0 ? 'active' : 'inactive'"></span>
                {{ scope.row.status === 0 ? '活跃' : '冻结' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
              label="最后登录"
              width="140"
              align="center"
          >
            <template #default="scope">
              <el-text size="small" type="info">
                {{ formatDate(scope.row.lastLoginTime) || '从未登录' }}
              </el-text>
            </template>
          </el-table-column>

          <el-table-column
              label="操作"
              width="200"
              align="center"
              fixed="right"
          >
            <template #default="scope">
              <div class="action-buttons">
                <el-tooltip content="编辑用户" placement="top">
                  <el-button
                      type="primary"
                      size="small"
                      @click="editUser(scope.row)"
                      :icon="Edit"
                      circle
                      plain
                  />
                </el-tooltip>

                <el-tooltip :content="scope.row.status === 0 ? '冻结用户' : '激活用户'" placement="top">
                  <el-button
                      :type="scope.row.status === 0 ? 'warning' : 'success'"
                      size="small"
                      @click="toggleUserStatus(scope.row)"
                      :icon="scope.row.status === 0 ? Lock : Unlock"
                      circle
                      plain
                  />
                </el-tooltip>

                <el-tooltip content="删除用户" placement="top">
                  <el-button
                      type="danger"
                      size="small"
                      @click="confirmDelete(scope.row)"
                      :icon="Delete"
                      circle
                      plain
                  />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-footer">
          <div class="footer-left">
            <div class="batch-actions" v-show="selectedUsers.length > 0">
              <el-text type="primary" class="selection-text">
                已选择 {{ selectedUsers.length }} 项
              </el-text>
              <div class="batch-buttons">
                <el-button
                    type="warning"
                    size="small"
                    @click="batchToggleStatus"
                    :icon="Lock"
                    plain
                >
                  批量冻结
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="batchDelete"
                    :icon="Delete"
                    plain
                >
                  批量删除
                </el-button>
              </div>
            </div>

            <div class="table-info" v-show="selectedUsers.length === 0">
              <el-text type="info" size="small">
                共 {{ totalUsers }} 条记录，当前第 {{ currentPage }} 页
              </el-text>
            </div>
          </div>

          <el-pagination
              class="pagination"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalUsers"
              background
              small
          />
        </div>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <user-edit-dialog
        v-model:visible="editDialogVisible"
        :user="selectedUser"
        :is-edit="isEditMode"
        @save="handleSaveUser"
        @success="handleUpdateSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  User,
  Plus,
  Edit,
  Delete,
  Search,
  Lock,
  Unlock,
  RefreshRight,
  UserFilled,
  Setting
} from '@element-plus/icons-vue';
import UserEditDialog from './UserEditDialog.vue';
import { getUsers, deleteUser, deleteUserByIds, updateUser } from "@/api/user";
import { debounce } from 'lodash-es';

// 响应式数据
const loading = ref(false);
const editDialogVisible = ref(false);
const isEditMode = ref(false);
const selectedUser = ref(null);
const userList = ref([]);
const selectedUsers = ref([]);
const searchKeyword = ref('');
const showFilters = ref(true);

// 筛选条件
const roleFilter = ref(null);
const statusFilter = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalUsers = ref(0);

// 计算属性 - 筛选后的用户列表
const filteredUserList = computed(() => {
  let filtered = [...userList.value];

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(user =>
        user.userName.toLowerCase().includes(keyword) ||
        user.id.toString().includes(keyword)
    );
  }

  // 角色筛选
  if (roleFilter.value !== null) {
    filtered = filtered.filter(user => user.role === roleFilter.value);
  }

  // 状态筛选
  if (statusFilter.value !== null) {
    filtered = filtered.filter(user => user.status === statusFilter.value);
  }

  return filtered;
});

// 生命周期
onMounted(() => {
  fetchUsers();
});

// 监听筛选条件变化，更新总数
watch(filteredUserList, (newList) => {
  totalUsers.value = newList.length;
}, { immediate: true });

// 方法定义
const fetchUsers = async () => {
  loading.value = true;
  try {
    const data = await getUsers();
    // 模拟完整的用户数据
    userList.value = data.map(user => ({
      ...user,
      avatar: user.avatar || `https://api.dicebear.com/7.x/avatars/svg?seed=${user.userName}`,
      createTime: user.createTime || new Date().toISOString(),
      lastLoginTime: user.lastLoginTime || null
    }));
    totalUsers.value = userList.value.length;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 防抖搜索
const handleSearch = debounce(() => {
  currentPage.value = 1; // 搜索时重置到第一页
}, 300);

// 筛选处理
const handleFilterChange = () => {
  currentPage.value = 1; // 筛选时重置到第一页
};

const resetFilters = () => {
  roleFilter.value = null;
  statusFilter.value = null;
  searchKeyword.value = '';
  currentPage.value = 1;
};

// 防抖获取用户数据
const debouncedFetchUsers = debounce(async () => {
  try {
    userList.value = await getUsers();
  } catch (error) {
    console.error('获取失败', error);
  }
}, 300);

// 处理更新成功
const handleUpdateSuccess = (isEdit) => {
  debouncedFetchUsers();
  ElMessage.success(isEdit ? '更新成功' : '添加成功');
};

// 工具函数
const getRoleTagType = (role) => {
  return role === 1 ? 'danger' : 'info';
};

const getRoleIcon = (role) => {
  return role === 1 ? Setting : UserFilled;
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  return new Date(dateString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
};

// 用户操作
const addUser = () => {
  isEditMode.value = false;
  selectedUser.value = {
    id: null,
    userName: '',
    role: 0,
    status: 0,
    avatar: '',
    createTime: new Date().toISOString()
  };
  editDialogVisible.value = true;
};

const editUser = (user) => {
  isEditMode.value = true;
  selectedUser.value = { ...user };
  editDialogVisible.value = true;
};

const handleSaveUser = (userData) => {
  if (isEditMode.value) {
    const index = userList.value.findIndex(u => u.id === userData.id);
    if (index !== -1) {
      userList.value[index] = { ...userData };
    }
  } else {
    const newId = Math.max(...userList.value.map(u => u.id)) + 1;
    userList.value.push({ ...userData, id: newId });
  }
};

// 切换用户状态
const toggleUserStatus = async (user) => {
  const action = user.status === 0 ? '冻结' : '激活';
  try {
    await ElMessageBox.confirm(
        `确定要${action}用户 "${user.userName}" 吗？`,
        `${action}确认`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    user.status = user.status === 0 ? 1 : 0;

    await updateUser(user);
    ElMessage.success(`用户已${action}`);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`);
    }
  }
};

// 删除确认
const confirmDelete = (user) => {
  ElMessageBox.confirm(
      `确定要删除用户 "${user.userName}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        dangerouslyUseHTMLString: true,
        center: true
      }
  ).then(() => {
    deleteUsers(user);
  });
};

const deleteUsers = async (user) => {
  try {
    await deleteUser(user.id);
    userList.value = userList.value.filter(u => u.id !== user.id);
    ElMessage.success(`用户 "${user.userName}" 已删除`);
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 批量操作
const batchToggleStatus = async () => {
  const activeUsers = selectedUsers.value.filter(u => u.status === 0);
  if (activeUsers.length === 0) {
    ElMessage.warning('请选择活跃状态的用户');
    return;
  }

  try {
    await ElMessageBox.confirm(
        `确定要冻结选中的 ${activeUsers.length} 个用户吗？`,
        '批量冻结确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    activeUsers.forEach(user => {
      user.status = 1;
    });

    ElMessage.success(`已冻结 ${activeUsers.length} 个用户`);
    selectedUsers.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量冻结失败');
    }
  }
};

const batchDelete = () => {
  ElMessageBox.confirm(
      `<div style="text-align: center;">
      <p style="margin: 10px 0; font-size: 16px;">确定要删除选中的 <strong>${selectedUsers.value.length}</strong> 个用户吗？</p>
      <p style="margin: 10px 0; color: #f56c6c; font-size: 14px;">⚠️ 此操作不可恢复！</p>
    </div>`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        dangerouslyUseHTMLString: true,
        center: true
      }
  ).then(async () => {
    try {
      const ids = selectedUsers.value.map(user => user.id);
      await deleteUserByIds(ids);
      userList.value = userList.value.filter(u => !ids.includes(u.id));
      selectedUsers.value = [];
      ElMessage.success(`已删除 ${ids.length} 个用户`);
    } catch (error) {
      ElMessage.error('批量删除失败');
    }
  });
};

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection;
};
</script>

<style scoped lang="scss">
.user-management-container {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);

  .user-card {
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: none;
    overflow: hidden;

    :deep(.el-card__header) {
      padding: 24px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      color: white;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 20px;

      .header-left {
        .card-title {
          margin: 0 0 8px 0;
          font-size: 24px;
          font-weight: 700;
          display: flex;
          align-items: center;
          gap: 12px;
          color: white;

          .title-icon {
            font-size: 28px;
          }
        }

        .subtitle {
          font-size: 14px;
          opacity: 0.9;
          color: rgba(255, 255, 255, 0.8);
        }
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 16px;

        .search-input {
          width: 280px;

          :deep(.el-input__inner) {
            border-radius: 20px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: black;

            &::placeholder {
              color: rgba(0, 0, 0, 0.6);
            }
          }
        }

        .add-btn {
          border-radius: 20px;
          padding: 12px 24px;
          background: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: white;
          font-weight: 600;
          backdrop-filter: blur(10px);

          &:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }

    :deep(.el-card__body) {
      padding: 0;
    }
  }

  .table-container {
    .filter-bar {
      padding: 20px 24px;
      background: #f8fafc;
      border-bottom: 1px solid #e2e8f0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      gap: 16px;

      .filter-group {
        display: flex;
        align-items: center;
        gap: 12px;

        .filter-label {
          font-weight: 500;
          color: #475569;
          min-width: 40px;
        }
      }

      .reset-filter-btn {
        color: #6366f1;

        &:hover {
          background: rgba(99, 102, 241, 0.1);
        }
      }
    }

    .modern-table {
      :deep(.el-table__header) {
        background: #f8fafc;

        th {
          background: #f8fafc !important;
          color: #475569;
          font-weight: 600;
          border-bottom: 2px solid #e2e8f0;
          padding: 16px 0;
        }
      }

      :deep(.el-table__body) {
        tr {
          transition: all 0.3s ease;

          &:hover {
            background: #f8fafc !important;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
          }

          td {
            padding: 16px 0;
            border-bottom: 1px solid #f1f5f9;
          }
        }
      }

      .user-avatar {
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.1);
        }
      }

      .user-info {
        .user-name {
          font-weight: 600;
          color: #1e293b;
          margin-bottom: 4px;
        }

        .user-meta {
          font-size: 12px;
        }
      }

      .el-tag {
        font-weight: 500;

        .tag-icon {
          margin-right: 4px;
        }
      }

      .status-dot {
        display: inline-block;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        margin-right: 6px;

        &.active {
          background: #10b981;
        }

        &.inactive {
          background: #ef4444;
        }
      }

      .action-buttons {
        display: flex;
        gap: 8px;
        justify-content: center;

        .el-button {
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 24px;
      background: #f8fafc;
      border-top: 1px solid #e2e8f0;

      .footer-left {
        flex: 1;

        .batch-actions {
          display: flex;
          align-items: center;
          gap: 20px;
          animation: slideInLeft 0.3s ease;

          .selection-text {
            font-weight: 600;
          }

          .batch-buttons {
            display: flex;
            gap: 12px;
          }
        }

        .table-info {
          animation: fadeIn 0.3s ease;
        }
      }

      .pagination {
        :deep(.el-pagination) {
          .el-pagination__sizes,
          .el-pagination__jump {
            .el-input__inner {
              border-radius: 6px;
            }
          }

          .btn-prev,
          .btn-next,
          .el-pager li {
            border-radius: 6px;
            margin: 0 2px;

            &.is-active {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              border-color: transparent;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .user-management-container {
    padding: 16px;

    .card-header {
      .header-actions {
        .search-input {
          width: 240px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 12px;

    .card-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-actions {
        flex-direction: column;
        gap: 12px;

        .search-input {
          width: 100%;
        }

        .add-btn {
          width: 100%;
          justify-content: center;
        }
      }
    }

    .filter-bar {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;

      .filter-group {
        flex-wrap: wrap;
      }
    }

    .table-footer {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .footer-left {
        .batch-actions {
          flex-direction: column;
          gap: 12px;

          .batch-buttons {
            justify-content: center;
          }
        }
      }

      .pagination {
        justify-content: center;

        :deep(.el-pagination) {
          justify-content: center;
        }
      }
    }
  }
}

// 动画效果
@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .user-management-container {
    background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);

    .user-card {
      :deep(.el-card__body) {
        background: #2d3748;
        color: #e2e8f0;
      }

      .filter-bar {
        background: #374151;
        border-color: #4b5563;
      }

      .table-footer {
        background: #374151;
        border-color: #4b5563;
      }
    }
  }
}
</style>